<?PHP
namespace app\system\controller;
use \think\Controller;
use think\Db;
use think\Session;
use think\Request;
use think\Cookie;

class Login extends Base {
    public function _initialize() {
        parent::_initialize ();
    }
    /**
     * 建站后台登录
     */
    public function  login(){
        $result = $this->validate($this->data,'Login.login');
        if(true !== $result){
            return api_return($result);
        }else{
            $result = model('Login')->login_check($this->data);
            if(is_array($result)){
               
                return api_return(11400,$result);
            }else{
                return api_return($result);
            }
        }
    }
    public function get_session(){
        $time = Session::get('test_session');
        echo json_encode($time);die;
    }
    public function test_session(){
        Session::init([
            'prefix'         => 'yali',
            'type'           => '',
            'auto_start'     => true,
            'expire	'  => 3600
        ]);
        Session::set('test_session','phper10000');
    }
    public function is_login(){

    }

    /********
     * @return mixed
     * 退出登录
     */
    public function login_out(){
        $result = $this->validate($this->data,'Login.login_out');
        if(true !== $result){
            return api_return($result);
        }else{
            $web = \app\system\model\Login::get_login_token($this->data['token']);
            if(!empty($web)){
                if(!empty($web['ucenter_token'])){
                    $ucenter_token = $web['ucenter_token'];
                    $mall_domain = \app\common\model\Base::get_domain_set();
                    $get_token_config = [
                        'client_id'  =>'ada75hfsdt834hg83gj43',
                        'token' =>  $ucenter_token
                    ];
                    $output = \app\common\model\Base::api_http(preg_http($mall_domain['ucenter_url']).'/client/auth/login_out',json_encode($get_token_config));
                }
//                if(!empty($output)) $output = \app\common\model\Base::object_array($output);
                \app\system\model\Login::del_login_token($this->data['token']);
                return api_return(11401);
            }else{
               return api_return(-13006);
            }
        }

    }



    /*******
     * @return mixed
     * 检测是否已登录(token)
     */
    public function load_auth(){
        //Cookie::set('name','abnccccc',3600);
        //echo json_encode(Cookie::get('name'));die;

//        $aaa = Request::instance()->header();
        $cookie = Request::instance()->cookie();
//        $cookie['h3s3xXls'] = 'a15c24841c245db4f1e07333772534f4';
//        echo json_encode($cookie);exit;
        if(!empty($cookie['h3s3xXls'])){
            $web = \app\system\model\Login::get_login_token($cookie['h3s3xXls']);
            if(!empty($web) && isset($web['identify'])){
                 if($web['identify']==0){
//                     echo json_encode($this->data);die;
                     $web_list = !empty($web['web_list'][$this->data['web_id']])?$web['web_list'][$this->data['web_id']]:[];
                     if(!empty($web_list['web_id']) && !empty($web['admin_uid']) && $web_list['web_id'] == $this->data['web_id'] ){
                         if(!empty($web['expire']) && $web['expire']>0 && $web['expire'] < request()->time()){
                             \app\system\model\Login::del_login_token($web['token']);
                             return api_return(-11409);
                         }else{
                             //替换主题信息
                             $web['web_id'] = $web_list['web_id'];
                             $web['temporary'] = $web_list['temporary'];
                             $web['name'] = $web_list['name'];
                             $web['head_photo'] = $web_list['head_photo'];
                             $web['domain'] = $this->data['domain'];
                             $web['site_type'] = $web_list['site_type']??0;
                             return api_return(11402,$web);
                         }

                     }else{
                         return api_return(-11406);
                     }
                 }elseif(in_array($web['identify'],[1,2,3,4])){
                     if(!empty($web['uid']) && $web['web_id'] == $this->data['web_id'] ){
                         if(!empty($web['expire']) && $web['expire']>0 && $web['expire'] < request()->time()){
                             \app\system\model\Login::del_login_token($web['token']);
                             return api_return(-11409);
                         }else{
                             return api_return(11402,$web);
                         }

                     }else{
                         return api_return(-11406);
                     }
                 }else{
                     return api_return(-11406);
                 }
            }else{
                return api_return(-11406);
            }

        }else{
            return api_return(-11409);
        }
    }


    /******
     * 保存菜单临时接口
     */
    public function save_menus(){
        $menu_list = Db::name('front_power')->where(['web_id'=>0,'type'=>'sys_manage','site_type'=>2,'member_type'=>0])->select();
        $menu_list = list_to_tree($menu_list);
        for($i=1;$i<=4;$i++){
            if($i!==2){
                foreach($menu_list as $v){
                    unset($v['id']);
                    $v['member_type'] = $i;
                        $new = $v;
                        if(isset($new['_child']))  unset($new['_child']);
                        $id = Db::name('front_power')->insertGetId($new);
                        if(!empty($v['_child'])){
                             foreach($v['_child'] as $vv){
                                 unset($vv['id']);
                                 $vv['member_type'] = $i;
                                 $vv['pid'] = $id;
                                 $new1 = $vv;
                                 if(isset($new1['_child']))  unset($new1['_child']);
                                 $id1 = Db::name('front_power')->insertGetId($new1);
                                 if(!empty($vv['_child'])){
                                     foreach($vv['_child'] as $vvv){
                                         unset($vvv['id']);
                                         $vvv['member_type'] = $i;
                                         $vvv['pid'] = $id1;
                                         $new2 = $vvv;
                                         if(isset($new2['_child']))  unset($new2['_child']);
                                         $id2 = Db::name('front_power')->insertGetId($new2);
                                     }
                                 }
                             }
                        }

                }
            }

        }
    }





    /*****
     * 获取后台菜单及其模型
     */
    public function get_menus(){
        $result = $this->validate($this->data,'Login.login_out');
        if(true !== $result){
            return api_return($result);
        }else{
            $res =[];
//            $member = cache($this->data['token'],'',get_cache_path(false));
            $member = \app\system\model\Login::get_login_token($this->data['token']);
            //获取用户类型所拥有的模型特权
            if(empty($member))   return api_return(-11406);
            if($member['identify']==0){
                foreach($member['web_list'] as $v){
                    if($v['temporary'] ==$this->data['domain']){
                        $site_type = $v['site_type'];
                    }
                }
                $menus = Db::name('front_power')->where(['type'=>'sys_manage','member_type'=>0,'site_type'=>$site_type,'status'=>1])->field('id,pid,name,type,flag,url,icon')->select();
                $menus = list_to_tree($menus);
                $res['menus'] = $menus;
                $set_ids = Db::name('front_power')->where(['type'=>'set','pid'=>0])->column('relation');
            }else{
                $site_type = \app\system\model\Login::get_site_type(['web_id'=>$this->data['web_id']]);
                if($site_type =='-11407'){
                    return api_return(-11407);
                }
                $own_power = Db::name('member_power')->where(['web_id'=>$member['web_id'],'type_id'=>$member['type_id'],'level_id'=>$member['level_id']])->find();
                $set_ids = [];
                if(!empty($own_power['publish'])){
                    $set_ids = Db::name('front_power')->where(['id'=>['in',$own_power['publish']],'pid'=>0])->column('relation');
                }
                if(!empty($own_power['manage'])){
                    $menus = Db::name('front_power')->where(['id'=>['in',$own_power['manage']],'status'=>1])->field('id,pid,name,type,flag,url,icon')->select();
                    $menus = list_to_tree($menus);
                    $res['menus'] = $menus;
                }

                $power_list = Db::name('front_power')->where(['web_id'=>$member['web_id'],'pid'=>0,'type'=>'set'])->column('relation','id');
                if(!empty($power_list)){
                    foreach($power_list as $k => $v){
                        $where = "type_id={$member['type_id']} and level_id={$member['level_id']} and find_in_set('{$k}',publish)";
                        $mp = Db::name('member_power')->where($where)->select();
                        if(!empty($mp))  unset($power_list[$k]);
                    }
                    $power_list = array_values($power_list);
                }
                $set_ids = array_merge($set_ids,$power_list);

            }
            $new_set_ids = ['product'=>[],'article'=>[],'link'=>[],'album'=>[],'form'=>[]];
            if(!empty($set_ids)){
//                fields_set_cache();
                $field_set = take_cache('fields_set',false);
                foreach($set_ids as $vv){
                    if(!empty($field_set[$vv])){
                        switch($field_set[$vv]['model_type']){
                            case 1:
                                $new_set_ids['product'][] = $vv;
                                break;
                            case 2:
                                $new_set_ids['article'][] = $vv;
                                break;
                            case 3:
                                $new_set_ids['link'][] = $vv;
                                break;
                            case 5:
                                $new_set_ids['album'][] = $vv;
                                break;
                            case 9:
                                $new_set_ids['form'][] = $vv;
                                break;
                            default:
                                break;
                        }
                    }
                }

            }

            $res['set_ids'] = $new_set_ids;

//            cache($member['token'],$member,get_cache_path(false));
            return api_return(10010,$res);
        }
    }

    /**
     * @return mixed
     * 通过token获取对应的的登录信息
     * wangruifang 临时方法
     */
    public function get_token(){
        //$result = $this->validate($this->data,'Login.login_out');
        if(empty($this->data['token'])){
            return api_return(-13001);
        }
        $web = \app\system\model\Login::get_login_token($this->data['token']);
        if(!empty($web)){
            return api_return(10007,$web);
        }else{
            return api_return(-10007);
        }
    }
    public function  oauth_login(){
//        return api_return(-18002);
//        print_r($this->data);die;
        if(!empty($this->data['access_token']) && !empty($this->data['domain'])){
            $access_token = $this->data['access_token'];
            if($access_token == 'undefined'){
                return api_return(-100000);
            }
            $data = $this->data;
            $mall_domain = \app\common\model\Base::get_domain_set('mall_domain',1);
            $output = \app\common\model\Base::curl_post($mall_domain.'/api/domain/get_domain_info',['domain'=>$data['domain']]);
            $output = \app\common\model\Base::object_array($output);

            if(!empty($output) && $output['code'] == 200){
                $data = array_merge($data,$output['data']);
                $output = $data;
            }else{
                return api_return($output['code']);
            }
//            return api_return(-18002,$data);
//            print_r($this->data);die;
            if(empty(session('user_info_'.$output['web_id']))){
                $output = model('client/Oauth')->get_user_info(['token'=>$access_token,'domain'=>$this->data['domain']]);
                if(!empty($output) && $output['code'] ==200 && !empty($output['data']['custom_id'])){
                    $data['admin_uid'] = $output['data']['custom_id'];
                    $data['ucenter'] = $data['access_token'];
                    $data['username'] =  !empty($output['data']['username'])?$output['data']['username']:'';
//                    return api_return(11400,$output);
//                    if($output['code'] == 200){
//                        $data = array_merge($data,$output['data']);
//                    }
                    unset($data['token']);
                    $data['token'] =  md5(create_random().request()->time().$data['username']);
                    model('system/Login')->token_recode($data);
                    session('user_info_'.$data['web_id'],$data);
//                    cookie('h3s3xXls',$data['token']);
//                    return api_return(-178788888,$access_token);
                }
//                return api_return(-1787878,$access_token);
            }else{
                $data = array_merge($data,session('user_info_'.$data['web_id']));
//                return api_return(-1140111,$data);
            }
            return api_return(11400,$data);
        }else{
            return api_return(-18002);
        }
    }

}